package logic

import (
	"context"
	"fmt"
	"net/http"
	"strconv"
	"zg4_month_exam/user/common"
	"zg4_month_exam/user/rpc/internal/models"

	"zg4_month_exam/user/rpc/internal/svc"
	"zg4_month_exam/user/rpc/pb/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddLogic {
	return &AddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddLogic) Add(in *user.AddRequest) (*user.Response, error) {
	// todo: add your logic here and delete this line
	switch in.Choose {
	case 1:
		//mysql同步es
		data, err, tx := models.GetProject()
		if err != nil {
			tx.Rollback() //错误回滚
			fmt.Println(err.Error())
		}
		for _, v := range data {
			err := common.EsAdd(in.Index, v, strconv.Itoa(v.Id))
			if err != nil {
				tx.Rollback() //错误回滚
				fmt.Println(err.Error())
			}
		}
		tx.Commit() //成功提交
		return &user.Response{
			Code: http.StatusOK,
			Msg:  "success",
		}, nil
	case 2:
		//首先创建分词索引
		err := common.EsPut(in.Index, in.Types, in.Analyzer)
		if err != nil {
			fmt.Println(err.Error())
		}
		return &user.Response{
			Code: http.StatusOK,
			Msg:  "success",
		}, nil
	case 3:
		//修改仓库名时需要同步es数据
		err := models.UpdateProject(in.Name, int(in.Id))
		if err != nil {
			fmt.Println("修改失败")
		}
		body := map[string]interface{}{
			"doc": map[string]interface{}{
				"Name": in.Name,
			},
		}
		err = common.EsUpdate(in.Index, body, strconv.Itoa(int(in.Id)))
		if err != nil {
			fmt.Println("es修改失败")
		}
		return &user.Response{
			Code: http.StatusOK,
			Msg:  "success",
		}, nil
	}

	return nil, nil
}
